<template>
  <div>
    <el-form :model="articleData" ref="formData" label-width="180px" label-position="right">
      <el-form-item label="标题：" prop="title" >
        <el-input v-model="articleData.title" placeholder="请输入标题" show-word-limit maxlength="50" />
      </el-form-item>
      <el-form-item label="摘要：" prop="summary">
        <el-input v-model="articleData.summary" placeholder="请输入摘要" show-word-limit maxlength="300" />
      </el-form-item>

      <el-form-item label="分类：" prop="checkedCategoryId">
        <el-select v-model="checkedCategoryId" clearable placeholder="请选择">
          <el-option
            v-for="item in categoryList"
            :key="item.categoryId"
            :label="item.categoryName"
            :value="item.categoryId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="标签：" prop="checkedLabelId">
        <el-select v-model="checkedLabelId" placeholder="请选择">
          <el-option
            v-for="item in labelList"
            :key="item.labelId"
            :label="item.labelName"
            :value="item.labelId">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="封面图：" prop="cover" >
        <el-upload class="avatar-uploader" action="" :show-file-list="false" :http-request="uploadMainImg">
          <img v-if="articleData.cover" :src="articleData.cover" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <el-button type="primary" size="small" @click="getDefaultImg"> 使用默认图片 </el-button>
      </el-form-item>

      <el-form-item label="文章类型：" prop="publicType">
        <el-radio-group v-model="articleData.articleType">
          <el-radio :label = "1">原创</el-radio>
          <el-radio :label = "2">转载</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="转载链接：" prop="curationLink" v-if = "articleData.articleType === 2">
        <el-input v-model="articleData.curationLink"
                  placeholder="请输入转载链接"
                  show-word-limit maxlength="200" />
      </el-form-item>

      <el-form-item label="公开类型：" prop="publicType">
        <el-radio-group v-model="articleData.publicType">
          <el-radio :label = "1">仅自己可见</el-radio>
          <el-radio :label = "2">组织内成员可见</el-radio>
          <el-radio :label = "3">所有人可见</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="是否允许评论：" prop="allowComment">
        <el-radio-group v-model="articleData.allowComment">
          <el-radio :label="1">允许</el-radio>
          <el-radio :label="0">不允许</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="是否允许下载：" prop="allowDownload">
        <el-radio-group v-model="articleData.allowDownload">
          <el-radio :label="1">允许</el-radio>
          <el-radio :label="0">不允许</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="是否定时发布：" prop="timedRelease">
        <el-radio-group v-model="articleData.timedRelease">
          <el-radio :label = "1">是</el-radio>
          <el-radio :label = "0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="是否审批通过后自动发布：" prop="autoPublish">
        <el-radio-group v-model="articleData.autoPublish">
          <el-radio :label = "1">是</el-radio>
          <el-radio :label = "0">否</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="定时发布时间：" prop="cronReleaseTime" v-if="articleData.timedRelease === 1">
        <el-date-picker v-model="articleData.cronReleaseTime" type="datetime" placeholder="选择发布时间">
        </el-date-picker>
      </el-form-item>

      <el-form-item label="内容：" prop="htmlContent" >
        <mavon-editor id="md" ref="md" v-model="articleData.mdContent" @change="getMdHtml"
                      @imgAdd="uploadContentImg"
                      @imgDel="delContentImg" />
      </el-form-item>

    </el-form>
    <el-row type="flex" justify="center">
      <el-button type="success" plain @click="submitDraft" :loading="loading" disabled>保存草稿</el-button>
      <el-button type="success" @click="submit()" :loading="loading">发布文章</el-button>
    </el-row>

  </div>
</template>

<script>
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
import { getInfoByCreaterId } from "@/api/category";
import { uploadFile, deleteFile } from "@/api/file";
import { listByCategoryId } from "@/api/label";
import { createArticle } from "@/api/article";
import { format } from "@/utils/date";
import { getLoginUserId } from "@/utils/userToken";
import { ARTICLE_IMG } from "@/utils/fileType";
import { getBaseSystemConfig } from '@/api/system';

export default {
  components:{
    mavonEditor, // 引入markdown编辑器
  },

  data() {
    return {
      articleData: {},     // 表单数据
      labelOptions:[],
      categoryList: [],
      labelList: [],
      checkedCategoryId: '',
      checkedLabelId: '',
      valid: true,
      loading: false
    };
  },

  created() {
    this.fetchCategory();
  },

  watch: {
    checkedCategoryId (newId, oldId) {
      this.checkedLabelId  = '';
      if (newId) {
        this.fetchLabel(newId);
      }
    }
  },

  methods: {
    // 获取所有的分类信息
    fetchCategory() {
      const userId = getLoginUserId();
      getInfoByCreaterId(userId).then(res => {
        if (res.code === 200) {
          this.categoryList = res.data;
        }
      })
    },

    getMdHtml(mdContent, htmlContent) {
      this.articleData.mdContent = mdContent;
      this.articleData.htmlContent = htmlContent;
    },

    // 根据分类信息的id查询标签信息
    fetchLabel(categoryId) {
      listByCategoryId(categoryId).then(response => {
        if (response.code === 200) {
          this.labelList = response.data;
        }
      })
    },

    // 使用默认图片
    getDefaultImg() {
      getBaseSystemConfig().then(res => {
        if (res.code === 200) {
          this.articleData.cover = res.data.articleDefaultCover;
          this.fetchCategory();
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
        }
      })
    },

    // 上传封面图
    uploadMainImg(file){
      const data = new FormData();
      data.append('file', file.file);
      data.append('type', ARTICLE_IMG);
      uploadFile(data).then(response => {
        // 将之前的图片删除
        // this.deleteImage();
        if(response.code === 200) {
          console.log(response.data)
          this.articleData.cover = response.data;
          this.fetchCategory();
        } else {
          this.$notify.error({
            title: '错误',
            message: response.message,
            duration: 1500
          });
        }
      }).catch(err => {
        this.$message({
          type: 'error',
          message: '上传失败'
        })
      })
    },

    uploadContentImg(pos,file){
      const fd = new FormData();
      fd.append('file',file);
      fd.append('type', ARTICLE_IMG);
      uploadFile(fd).then(resp => {
        if(resp.code === 200) {
          this.$refs.md.$img2Url(pos, resp.data);
        }
      })
    },

    delContentImg(urlAndFileArr){
      const fileUrl = urlAndFileArr[0];
      const file = urlAndFileArr[1];
      console.log('删除图片',fileUrl,file);
      deleteFile(fileUrl);
    },

    // 发布文章
    submit() {
      this.loading = true;
      this.beforeSubmit();
      if (!this.valid) {
        this.valid = true;
        return;
      }
      this.articleData.categoryId = this.checkedCategoryId;
      this.articleData.labelId = this.checkedLabelId;
      if (this.articleData.cronReleaseTime) {
        this.articleData.cronReleaseTime = format(this.articleData.cronReleaseTime);
      }

      createArticle(this.articleData).then(res => {
        if (res.code === 200) {
          this.$notify({
            title: '成功',
            message: '文章发表成功，等待管理员审核',
            type: 'success',
            duration: 1500
          });
          this.loading = false;
          this.$router.replace({path: '/article/list'});
        } else {
          this.$notify.error({
            title: '错误',
            message: res.message,
            duration: 1500
          });
          this.loading = false;
        }
      })
    },

    // 发布文章（草稿）
    submitDraft() {

    },


    beforeSubmit() {
      if (!this.articleData.title) {
        this.$notify.error({
          title: '错误',
          message: '请输入标题',
          duration: 1500
        });
        this.valid = false;
        return
      }

      if (!this.checkedCategoryId) {
        this.$notify.error({
          title: '错误',
          message: '请选择分类',
          duration: 1500
        });
        this.valid = false;
        return
      }

      if (!this.checkedLabelId) {
        this.$notify.error({
          title: '错误',
          message: '请选择标签',
          duration: 1500
        });
        this.valid = false;
        return
      }

      if (!this.articleData.cover) {
        this.$notify.error({
          title: '错误',
          message: '请上传封面图',
          duration: 1500
        });
        this.valid = false;
        return
      }

      if (!this.articleData.publicType) {
        this.$notify.error({
          title: '错误',
          message: '请选择公开类型',
          duration: 1500
        });
        this.valid = false;
        return
      }

      if (this.articleData.allowComment !== 0 && this.articleData.allowComment !== 1) {
        this.$notify.error({
          title: '错误',
          message: '请选择是否允许评论',
          duration: 1500
        });
        this.valid = false;
        return
      }

      if (this.articleData.timedRelease !== 1 && this.articleData.timedRelease !== 0) {
        this.$notify.error({
          title: '错误',
          message: '请选择是否定时发布',
          duration: 1500
        });
        this.valid = false;
        return
      }

      if (this.articleData.timedRelease && !this.articleData.cronReleaseTime) {
        this.$notify.error({
          title: '错误',
          message: '请选择定时发布时间',
          duration: 1500
        });
        this.valid = false;
        return
      }

      if (this.articleData.autoPublish !== 0 && this.articleData.autoPublish !== 1) {
        this.$notify.error({
          title: '错误',
          message: '请选择是否审批通过后自动发布',
          duration: 1500
        });
        this.valid = false;
        return
      }

      if (!this.articleData.htmlContent) {
        this.$notify.error({
          title: '错误',
          message: '请输入文章内容',
          duration: 1500
        });
        this.valid = false;
      }
    },


  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
